use crate::utils::dbus_polkit::polkit_check_auth;
use tokio::process::Command;
use std::path::Path;

pub async fn install_package(path: &str) -> Result<(), String> {
    let path = Path::new(path);
    if !path.exists() {
        return Err("文件不存在".into());
    }

    // 沙盒冲突检测
    if let Some(conflict_pid) = crate::core::sandbox::check_conflict(path) {
        return Err(format!("检测到沙盒冲突 (PID: {})", conflict_pid));
    }

    // Polkit 提权
    if !polkit_check_auth("安装玲珑包需要管理员权限").await? {
        return Err("用户取消授权".into());
    }

    // 执行安装命令
    let mount_output = Command::new("ll-cli")
        .arg("mount")
        .arg(path)
        .output()
        .await
        .map_err(|e| e.to_string())?;
    
    if !mount_output.status.success() {
        return Err(String::from_utf8_lossy(&mount_output.stderr).into());
    }

    let install_output = Command::new("ll-cli")
        .arg("install")
        .arg(path)
        .output()
        .await
        .map_err(|e| e.to_string())?;
    
    if install_output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&install_output.stderr).into())
    }
}